<?php
    /**
     * =====================================================================
     * Load Theme specific-settings
     */
    define('inc',trailingslashit(get_template_directory()).'inc/');
    load_template(inc . 'load_sidebars.php');
    load_template(inc . 'load_widgets.php');
    load_template(inc . 'load_custom_scripts.php');
    load_template(inc . 'load_custom_tables.php');
    load_template(inc . 'load_metadatas.php');
    load_template(inc . 'load_custom_post_types.php');
    load_template(inc . 'load_schedules.php');
    load_template(inc . 'shortcodes.php');    
    
    /**
     * REDIRECT
     */
    add_action('init', 'cpx_redirect_mask');
    function cpx_redirect_mask()
    {
        $request = $_SERVER['REQUEST_URI'];
        $request_arr = explode('/', $request);
        // Redirect to store url with aff link
        if($request_arr[count($request_arr) - 2] == 'go')
        {
            $id = $request_arr[count($request_arr) - 1];
            $org_link = get_post_meta($id, 'store_homepage_metadata', true);
            if ($org_link)
				wp_redirect($org_link, 301);
			exit;
        }
        // Redirect deal checkout
        else if($request_arr[count($request_arr) - 2] == 'checkout')
        {
            $last_para = $request_arr[count($request_arr) - 1];
            $arr_last_para = explode("-",$last_para);
            if(count($arr_last_para) == 1)
            {
                $post_id = $last_para;
                $org_link = get_post_meta($post_id, 'link_checkout_metadata', true);            
                if($org_link)
                    wp_redirect($org_link, 301);
                exit;
            }                
            else if(count($arr_last_para) == 2)
            {
                $post_id = $arr_last_para[0];                
                $version = substr($arr_last_para[1],1);
                
                $org_link = get_post_meta($post_id, 'l'.$version, true);
                if($org_link)
                    wp_redirect($org_link, 301);
                exit;
            }
        }
    }
    /**
     * GET CURRENT URL
     * @return URL
     */
    function cpx_current_url() {
        $pageURL = 'http';
        if ($_SERVER["HTTPS"] == "on") {
            $pageURL .= "s";
        }
        $pageURL .= "://";
        if ($_SERVER["SERVER_PORT"] != "80") {
            $pageURL .= $_SERVER["SERVER_NAME"] . ":" . $_SERVER["SERVER_PORT"] . $_SERVER["REQUEST_URI"];
        } else {
            $pageURL .= $_SERVER["SERVER_NAME"] . $_SERVER["REQUEST_URI"];
        }
        return $pageURL;
    }
    
    /**
     * CALCULATE WEBSITE LOADING TIME
     */
    function cpx_cal_loading_time() {
        //if (current_user_can('administrator'))
        //{
        global $wpdb;
        // Get the total page generation time
        $totaltime = timer_stop(false, 22);
        // Calculate the time spent on MySQL queries by adding up the time spent on each query
        $mysqltime = 0;
        // if there are indeed mysql queries then
        if ($wpdb->queries != null)
            foreach ($wpdb->queries as $query)
                $mysqltime = $mysqltime + $query[1];
        // The time spent on PHP is the remainder
        $phptime = $totaltime - $mysqltime;
        // Create the percentages
        $mysqlper = number_format_i18n($mysqltime / $totaltime * 100, 2);
        $phpper = number_format_i18n($phptime / $totaltime * 100, 2);
        // Output the stats
        echo 'Page generated in ' . number_format_i18n($totaltime, 4) . " seconds ( {$phpper}% PHP, {$mysqlper}% MySQL )";
        //}
    }
    
    //word limit
    function truncate_str($str, $maxlen ,$end_char = '&#8230;') {
        if (strlen($str) <= $maxlen)
            return $str;
        $newstr = substr($str, 0, $maxlen);
        if (substr($newstr, -1, 1) != ' ')
            $newstr = substr($newstr, 0, strrpos($newstr, " "));
        return $newstr . $end_char;
    }
    
    /**
     * HIGHLIGHT SEARCH KEYWORD
     */
    function cpx_remove_non_AlphaNumeric($string) {
        return preg_replace("/[^A-Za-z0-9 ]/", '', $string);
    }
    
    function cpx_highligh_keyword($text, $kw) {
        $kw = cpx_remove_non_AlphaNumeric($kw);
        $kw = explode(" ", $kw);
        $text = preg_replace('/(' . implode('|', $kw) . ')/iu', '<strong class="search-highlight-kw">\0</strong>', $text);
        echo $text;
    }

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    /**
     * GET DEALS BY STORE
     */
    function cpx_get_deals($store_id = '', $number_to_show = -1, $ignore_sticky_deal = 1, $deal_status = 'active', $comming = 0, $return_array = false, $get_past_deals = false, $random = false, $exclude_ids = array()) {
        $paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
        $meta_query = array(
            array(
                'key' => 'status_metadata',
                'value' => "$deal_status",
                'compare' => '=')
        );
        // If get deals by store id
        if (!empty($store_id)) {
            $get_deals_by_st_id = array(
                'key' => 'store_id_metadata',
                'value' => $store_id,
                'compare' => '=');
            array_push($meta_query, $get_deals_by_st_id);
        }
        //if comming soon
        if($comming == 1){
            $today = date('Y/m/d');
            $get_comming_soon = array(
                'key' => 'start_date_metadata',
                'value' => $today,
                'compare' => '>'
            );
            array_push($meta_query, $get_comming_soon);
        }
        // if get past deals
        if($get_past_deals == true){
            $today = date('Y/m/d');
            $past_deal = array(
                'key' => 'end_date_metadata',
                'value' => $today,
                'compare' => '<'
            );
            array_push($meta_query, $past_deal);
        }
        
        $args = array(
            'post_type' => 'post',
            'post_status' => 'publish',
            'orderby' => 'date',
            'order' => 'DESC',
            'posts_per_page' => $number_to_show,
            'meta_query' => $meta_query,
        );
        if($random == true)
        {
            $args['orderby'] = 'rand';
        }
        if($exclude_ids)
        {
            $args['post__not_in'] = $exclude_ids;
        }
        // Ignore sticky deal
        if ($ignore_sticky_deal == 1) {
            $args['post__not_in'] = get_option('sticky_posts');
        }
        //Pagination
        if ($number_to_show != -1) {
            //$args['posts_per_page'] = $number_to_show;
            $args['paged'] = $paged;
        }
        
        $query = new WP_Query($args);
        // use for cpx_get_past_deals()
        if($return_array == true)
        {
            $arr = array();
            foreach ($query->posts as $p) {
                array_push($arr, $p->ID);
            }
            return $arr;
        }
        //
        $total_pages = $query->max_num_pages;
        ?>
        <div class="all-deals-list row-fluid">
        <?php
        
        if ($query->have_posts())
        {
            if($comming == 1)
            {
                foreach ($query->posts as $p) {
                    cpx_get_deal_info($p->ID, 1, 0, '', 1);
                }                
            }
            else
            {
                if($get_past_deals == true)
                {
                    foreach ($query->posts as $p) {
                        cpx_get_deal_info($p->ID, 0, 0, '', 1);
                    }
                }
                else
                {
                    foreach ($query->posts as $p) {
                        cpx_get_deal_info($p->ID);
                    }
                }                
            }        
        }
        ?>
        </div>
        <?php
        if ($number_to_show != '') {
            pagination($total_pages, 2);
        }
    }
    
    /**
     * GET PAST DEALS
     */
    function cpx_get_past_deals($cat_id) {
        $arr = array();
        $stores_by_cat = cpx_get_stores_by_cat($cat_id);
        if (count($stores_by_cat) > 0) 
        {
            foreach ($stores_by_cat as $p)
            {
                $arr_deactive_deal_ids = cpx_get_deals($p->ID, -1, 1, 'deactive', 0, true, true);
                if(count($arr_deactive_deal_ids) > 0)
                    $arr = array_merge($arr, $arr_deactive_deal_ids);
            }
        }
        return $arr;
    }
    function cpx_get_comming_soon_deals($cat_id) {
        $arr = array();
        $stores_by_cat = cpx_get_stores_by_cat($cat_id);
        if (count($stores_by_cat) > 0) 
        {
            foreach ($stores_by_cat as $p)
            {
                $arr_deactive_deal_ids = cpx_get_deals($p->ID, -1, 1, 'deactive', 1, true, false);
                if(count($arr_deactive_deal_ids) > 0)
                    $arr = array_merge($arr, $arr_deactive_deal_ids);
            }
        }
        return $arr;
    }
    function cpx_get_active_deals($cat_id) {
        $arr = array();
        $stores_by_cat = cpx_get_stores_by_cat($cat_id);
        if (count($stores_by_cat) > 0) 
        {
            foreach ($stores_by_cat as $p)
            {
                $arr_deactive_deal_ids = cpx_get_deals($p->ID, -1, 1, 'active', 0, true, false);
                if(count($arr_deactive_deal_ids) > 0)
                    $arr = array_merge($arr, $arr_deactive_deal_ids);
            }
        }
        return $arr;
    }

    function cpx_get_stores_by_cat($cat_id) {
        $args = array(
            'post_type' => 'store',
            'post_status' => 'publish',
            'posts_per_page' => -1,
            'category' => $cat_id,
            'orderby' => 'post_date',
            'order' => 'DESC');
        $stores = get_posts($args);
        return $stores;
    }

/**
 * PRINT ALL CATEGORIES AS LINKS
 */
function cpx_print_categories($exclude_uncategorized = 1, $filter_by_past_deal = 0) {
    $args = array(
        'type' => 'post',
        'child_of' => 0,
        'parent' => '',
        'orderby' => 'name',
        'order' => 'ASC',
        'hide_empty' => 1,
        'hierarchical' => 1,
        'include' => '',
        'number' => '',
        'taxonomy' => 'category',
        'pad_counts' => false
    );
    if ($exclude_uncategorized == 1) {
        $args['exclude'] = 1;
    } else {
        $args['exclude'] = '';
    }
    $cats = get_categories($args);
    if ($filter_by_past_deal == 0) {
        foreach ($cats as $c) {
            $term_link = get_term_link($c, 'category');
            $cat_name = $c->name;
            echo "<span class=''><a class='list-by-category' title='See all deals of {$cat_name}' href='$term_link'>$cat_name</a></span>";
        }
    } else if ($filter_by_past_deal == 1) {
        foreach ($cats as $c) {
            $cat_name = $c->name;
            $cat_id = $c->term_id;
            $term_link = site_url('/past-deals?cat=') . $cat_id;
            echo "<span class=''><a class='list-by-category' title='See past deals of {$cat_name}' href='{$term_link}'>$cat_name</a></span>";
        }
    }
}
    /**
     * GET DEAL INFO
     */
    function cpx_get_deal_info($deal_id, $show_count_down = 1, $show_at_sidebar = 0, $search_kw = '', $is_coming_soon = 0)
    {
        $link_deal_detail = get_permalink($deal_id);
        $title = get_the_title($deal_id);
        $value_after_saved = round(get_post_meta($deal_id, 'after_discount_metadata', true),2);
        $start_date = get_post_meta($deal_id, 'start_date_metadata', true);
        $end_date = get_post_meta($deal_id, 'end_date_metadata', true);
        $image = get_post_meta($deal_id, 'deal_feature_metadata', true);
        
        if($show_at_sidebar == 0):
        ?>
        <ul class="single-deal">
            <li>
                <span class="image-wrap">
                    <a href="<?php echo $link_deal_detail; ?>" title="<?php echo $title; ?>">
                        <img src="<?php echo $image;?>" title="<?php echo $title;?>"/>
                    </a>
                </span>
                <div class="recent-deal-title">
                    <a href="<?php echo $link_deal_detail; ?>" title="<?php echo $title; ?>"><?php echo ($search_kw != '' ? cpx_highligh_keyword($title, $search_kw) : $title); ?></a>
                </div>
        <?php if ($show_count_down == 1): ?>
                    <div class="another-timer-block">
                        <div id="count_down_<?php echo $deal_id; ?>" class="time-count">
                            <?php
                                if($is_coming_soon == 0)
                                    cpx_get_count_down($deal_id, $end_date);
                                else echo "<strong>Start&nbsp:&nbsp</strong>".$start_date;
                            ?>
                        </div>
                    </div>
                    <a href="#" class="right-see-btn"></a>
        <?php endif; ?>
            </li>
        </ul>
        <div class="hr"></div>
        <?php
        // DISPLAY AT RIGHT SIDE BAR
        elseif ($show_at_sidebar == 1):
            ?>
            <div class="right-sidebar-content">
                <div class="right-wrapper">
                    <a class="" href="<?php echo $link_deal_detail; ?>" title="<?php echo $title; ?>">
                        <img src="<?php echo $image;?>" title="<?php echo $title;?>"/>
                        <span class="right-deal-title"><?php echo $title; ?></span>
                    </a>
                    <div class="right-timer-block">
                        <?php if($show_count_down == 1): ?>
                        <div class="right-timer-msg" id="count_down_<?php echo $deal_id;?>">
                            <?php
                            if($is_coming_soon == 0) 
                                cpx_get_count_down($deal_id, $end_date);
                            elseif($is_coming_soon == 1)
                                echo "<strong>Start&nbsp:&nbsp</strong>".$start_date;
                            ?>
                        </div>
                    <?php endif; ?>
                    </div>
                    <a href="<?php echo $link_deal_detail; ?>" class="right-see-btn"></a>
                </div>
            </div>
            <hr/>
            <?php
        endif;
    }

    /**
     * GET COUNT DOWN
     */
    function cpx_get_count_down($deal_id, $end_date = '') {
        if (!empty($end_date)) {
            $arr_enddate = explode('/', $end_date);
            if (count($arr_enddate) == 3) {
                $y = $arr_enddate[0];
                $m = $arr_enddate[1];
                $d = $arr_enddate[2];
                $h = 24;
            }
            ?>
            <script type="text/javascript">
                jQuery(document).ready(function($) {
                    var id = <?php echo $deal_id; ?>;
                    var y = <?php echo $y; ?>;
                    var m = <?php echo $m; ?>;
                    var d = <?php echo $d; ?>;
                    var h = <?php echo $h; ?>;
                    var end_time = new Date(y, m - 1, d, h);
                    $('#count_down_' + id).countdown({
                        until: end_time
                    });
                });
            </script>
            <?php
        } else {
            echo 'Unlimited time';
        }
    }
    
    /**
     * Pagination
     */
    if (!function_exists('pagination')) {   
        function pagination($pages = '', $range = 4) {
            $showitems = ($range * 2) + 1;
            global $paged;
            if (empty($paged))
                $paged = 1;
            if ($pages == '') {
                global $wp_query;
                $pages = $wp_query->max_num_pages;
                if (!$pages) {
                    $pages = 1;
                }
            }
            if (1 != $pages) {
                echo "<div class='pagination'>";
                echo "<div class=\"page_nav\">";
                if ($paged > 2 && $paged > $range + 1 && $showitems < $pages)
                    echo "<a title='First' href='" . get_pagenum_link(1) . "' class=\"prev page-numbers\">First</a>";
                if ($paged > 1 && $showitems < $pages)
                    echo "<a title='Previous' href='" . get_pagenum_link($paged - 1) . "' class=\"page-numbers dots\">&lsaquo;&lsaquo;</a>";
                for ($i = 1; $i <= $pages; $i++) {
                    if (1 != $pages && (!($i >= $paged + $range + 1 || $i <= $paged - $range - 1) || $pages <= $showitems )) {
                        echo ($paged == $i) ? "<span class=\"page-numbers current\">" . $i . "</span>" : "<a title='page-" . $i . "' href='" . get_pagenum_link($i) . "' class=\"page-numbers\">" . $i . "</a>";
                    }
                }
                if ($paged < $pages && $showitems < $pages)
                    echo "<a title='Next' href=\"" . get_pagenum_link($paged + 1) . "\" class=\"page-numbers dots\">&rsaquo;&rsaquo;</a>";
                if ($paged < $pages - 1 && $paged + $range - 1 < $pages && $showitems < $pages)
                    echo "<a title='Last' href='" . get_pagenum_link($pages) . "' class=\"next page-numbers\">Last</a>";
                echo "</div>\n";
                echo "</div>\n";
            }
        }
    
    }
/* Pagination custom */
if (!function_exists('pagination_custom')) {

    function pagination_custom($url, $page, $pages, $current, $range = 4) {
        $showitems = ($range * 2) + 1;
        echo "<div class=\"pagination\">";
        echo "<div class=\"page_nav\">";
        if ($current != 1 && $showitems < $pages) {
            echo "<a title='First' href='$url' class=\"prev page-numbers\">First</a>";
            if ($current != 2) {
                echo "<a title='Previous' href='$url?page=" . ($page - 1) . "' class=\"prev page-numbers\">&lsaquo;&lsaquo;</a>";
            } else {
                echo "<a title='Previous' href='$url' class=\"prev page-numbers\">&lsaquo;&lsaquo;</a>";
            }
        }
        for ($i = 1; $i <= $pages; $i++) {
            if (1 != $pages && (!($i >= $page + $range + 2 || $i <= $page - $range) || $pages <= $showitems )) {
                if ($current != $i) {
                    if ($i == 1) {
                        echo "<a title='page-$i' href='$url' class=\"page-numbers\">$i</a>";
                    } else {
                        echo "<a title='page-$i' href='$url?page=$i' class=\"page-numbers\">$i</a>";
                    }
                } else {
                    echo "<span class=\"page-numbers current\">" . $i . "</span>";
                }
            }
        }
        if ($current != $pages && $showitems < $pages) {
            if ($current != 1) {
                echo "<a title='Next' href='$url?page=" . ($page + 1) . "' class=\"prev page-numbers\">&rsaquo;&rsaquo;</a>";
            } else {
                echo "<a title='Next' href='$url?page=" . ($page + 2) . "' class=\"prev page-numbers\">&rsaquo;&rsaquo;</a>";
            }
            echo "<a title='Last' href='$url?page=" . ($pages) . "' class=\"prev page-numbers\">Last</a>";
        }
        echo "</div>\n";
        echo "</div>\n";
    }

}
    /**
     * GET RELATED STORES
     * @todo Get related stores
     * @return Array store ids
     */
    function cpx_get_relate_store($store_id, $itemsToShow = -1) {
        // get stores have coupons
        $arr_st_have_deal = cpx_get_store_have_deals();
        // remove current store id from array
        $arr_st_have_deal = array_diff($arr_st_have_deal, array($store_id));
        
        // get the custom post type's taxonomy terms             
        $custom_taxterms = wp_get_object_terms($store_id, 'category', array('fields' => 'ids'));
        // arguments
        $args = array(
            'post_type' => 'store',
            'post_status' => 'publish',
            'posts_per_page' => $itemsToShow,
            'orderby' => 'rand',
            'tax_query' => array(
                array(
                    'taxonomy' => 'category',
                    'field' => 'id',
                    'terms' => $custom_taxterms
                )
            ),
            'post__in' => $arr_st_have_deal
        );
        $related_items = new WP_Query($args);
        $arr_st_ids = array();
        if ($related_items->have_posts()) {
            foreach ($related_items->posts as $p) {
                array_push($arr_st_ids, (int) $p->ID);
            }
        }
        return $arr_st_ids;
    }
    /**
     * GET RELATED DEALS
     */
    function cpx_get_related_deals($store_id, $exclude_current_dealID, $from_number_store = -1, $number_deals_to_show = -1)
    {
        $related_store_ids = cpx_get_relate_store($store_id, $from_number_store);
        if(count($related_store_ids) > 0)
        {
            $related_deal_ids = array();
            $meta_query = array(
                    array(
                        'key' => 'store_id_metadata',
                        'value' => $related_store_ids,
                        'compare' => 'IN'),
                    array(
                        'key' => 'status_metadata',
                        'value' => "active",
                        'compare' => '=')
                );
                $args = array(
                    'post_type' => 'post',
                    'post_status' => 'publish',
                    'orderby' => 'date',
                    'order' => 'DESC',
                    'posts_per_page' => $number_deals_to_show,
                    'meta_query' => $meta_query,
                    'post__not_in' => array($exclude_current_dealID)
                );
                
                $qr = new WP_Query($args);
                if($qr->have_posts())
                {
                    foreach ($qr->posts as $p) {
                        array_push($related_deal_ids, $p->ID);
                    }                     
                    return $related_deal_ids;
                }               
        }
        
    }
    /**
     * GET STORES HAVE DEALS
     * @return Array store ids
     */
    function cpx_get_store_have_deals() {
        global $wpdb;
        $qr = "SELECT meta_value AS 'ID' FROM {$wpdb->postmeta}  WHERE meta_key = 'store_id_metadata' GROUP BY meta_value;";
        $rs = $wpdb->get_results($qr);
        $arr_st_ids = array();
        if (count($rs) > 0) {
            foreach ($rs as $p) {
                array_push($arr_st_ids, $p->ID);
            }
        }
        return $arr_st_ids;
    }

    /**
     * HOOK TO SEARCH QUERY
     */
    add_filter('pre_get_posts', 'search_filter');
    
    function search_filter($query) {
        if ($query->is_main_query()) {
            if ($query->is_search()) {
                global $query;
                $kw = get_search_query();
                $limit = "LIMIT 0,99";
                $query = cpx_search_query_store($kw, $limit);
            }
        }
        return $query;
    }

    function cpx_search_query_store($keyword, $limit = "LIMIT 0,99") {
        global $wpdb;
        $query = "
        SELECT 
            p.ID,p.post_type
        FROM
            {$wpdb->posts} AS p,
            {$wpdb->postmeta} AS m 
        WHERE p.`ID` = m.`post_id` 
            AND p.`post_type` IN ('store','post') 
            AND p.`post_status` = 'publish' 
            AND (p.`post_title` LIKE '%$keyword%' OR p.post_content LIKE '%$keyword%')
        GROUP BY p.ID
        ORDER BY p.post_type DESC $limit;
        ";
            return $query;
    }
    /**
     * GET COMING SOON DEALS
     */
    function cpx_get_comingsoon_deals()
    {
        global $wpdb;
        $d = date('y/m/d');
        $qr = "
        SELECT p.ID FROM {$wpdb->posts} AS p,{$wpdb->postmeta} AS m
        WHERE p.`ID` = m.`post_id`
        AND
        (
        	m.`meta_key` = 'start_date_metadata'
        	AND
        	CAST(m.`meta_value` AS DATE) > '$d'
        )
        AND p.`post_status` = 'publish'
        ";
        $rs = $wpdb->get_results($qr);
        return $rs;
    }
    /**
     * ADD SUBSCRIBE EMAIL
     */
    function add_subscribe_email($email = '', $ip_address = '')
    {
        $time = current_time('mysql');            
        $arr_values = array('user_email' => $email, 'time'=> $time, 'user_ip' => $ip_address, 'follow_what' => 'site');
        global $wpdb;
        $insert = $wpdb->insert($wpdb->prefix.'follow', $arr_values);
        return $insert;
    }
    /**
     * Filter deal extra fields
     * @return Array s = $save, $va = value after save, $d = % discount
     */
    function get_deal_values($discount, $value)
    {
        $arr_return = array();
        
        $d = $discount;
        $va = round($value - (($value*$d)/100),2);
        $s = round($value - $va);
        
        $arr_return['d'] = $d;
        $arr_return['s'] = $s;
        $arr_return['va'] = $va;
        
        return $arr_return;
    }
    function cpx_filter_extra_fields($ex, $discount)
    {
        $arr = array();
        $ex = explode(";", $ex);    
        foreach ($ex as $e) 
        {
            if(trim($e) != '')
            {
                $t = explode("|", $e);
                $text = trim($t[0]);
                $value = trim($t[1]);
                $link = trim($t[2]);
                $d = $discount;
                
                $arr_price = get_deal_values($d, $value);
                $arr_price['t'] = $text;
                $arr_price['l'] = $link;
                $arr_price['v'] = $value;
                array_push($arr, $arr_price);
            }
        }
        return $arr;
    }
    /**
     * ADD STORE MASK LINK
     */
    add_action('save_post', 'add_store_mask_link');
    add_action('new_to_publish', 'add_store_mask_link');
    add_action('draft_to_publish', 'add_store_mask_link');
    add_action('pending_to_publish', 'add_store_mask_link');
    function add_store_mask_link($post)
    {
        if(is_object($post))
            $st_id = $post->ID;
        else
            $st_id = $post;
        $mask = site_url('/go/'.$st_id);
        add_post_meta($st_id, 'store_mask_metadata', $mask, true);
    }
    // GET DEAL MASK LINK
    function cpx_get_deal_mask_link($post_id, $is_extra_link = false, $version = 0)
    {
        if(!$is_extra_link)
            return site_url("/checkout/$post_id");
        else if($is_extra_link)
            return site_url("/checkout/{$post_id}-v{$version}");
    }
    //////////////////////////////////////////////////////////////////////////////
    function cpx_read_xml($file_path, $aff_network = 'avangate', $cp, $sort)
    {
        $arr = array();
        if($aff_network == 'avangate')
        {
            $xml = simplexml_load_file($file_path);
            
            foreach ($xml->Vendors->Vendor->Products->children() as $x) {
                $temp_arr = array();
                $temp_arr['name'] = (string)$x->Name;
                $temp_arr['price'] = (string)$x->Price;
                
                $aff = (string)$x->AffiliateBuyLink;
                $aff .= "&COUPON=".$cp;
                $temp_arr['aff'] = $aff;
                array_push($arr, $temp_arr);
            }
        }
        else if($aff_network == 'regnow')
        {
            $xml = simplexml_load_file($file_path);
            //$arr = array();
            foreach ($xml->children() as $x) {
                $temp_arr = array();
                $a = (array)$x;
                $a = $a['@attributes'];
                
                $temp_arr['name'] = $a['ProductName'];
                $temp_arr['price'] = $a['USDPrice'];
                
                $aff = $a['DirectPurchaseURL'];
                $aff .= "&ss_coupon=".$cp;
                $temp_arr['aff'] = $aff;
                array_push($arr, $temp_arr);
            }
        }
        function mysort($a, $b) {
            return $a["price"] > $b["price"];
        }
        if($sort == 'true')
            usort($arr,'mysort');
        return $arr;
    }
    //cpx_read_xml('http://www.markcoupons.com/wp-content/uploads/2013/12/regnow_602618_auto_800a166e5edfe3a63d60703777afa1075ec1a34e.xml','regnow','haiht');
    
    /**
     * Dashboard Support
     **/
    add_action('wp_dashboard_setup', 'support_dashboard_widgets');
 
    function support_dashboard_widgets() {
        wp_add_dashboard_widget('custom_support', 'Custommer Suport', 'support_dashboard');
    }

    function support_dashboard() {
        global $wpdb,$table_prefix;
        $my_query = "SELECT ".$table_prefix."contact.name,".$table_prefix."contact.email,
            ".$table_prefix."contact.subject,".$table_prefix."contact.message,".$table_prefix."contact.time 
            FROM ".$table_prefix."contact  WHERE ".$table_prefix."contact.issue ='support' 
            ORDER BY ".$table_prefix."contact.time DESC LIMIT 0,10";
        $result = $wpdb->get_results($my_query); ?>
        <div id="published-posts" class="activity-block" style="max-height:340px;overflow:auto;">
        <?php 
        foreach ($result as $rs){ ?>
            <div>
                <div class="name">
                    <span><b>Name&nbsp;:</b>&nbsp;<?php echo $rs->name;?></span>
                    <span>&nbsp;(&nbsp;<?php echo $rs->time;?>&nbsp;)&nbsp;</span>
                </div>
                <div class="emai"><b>Email&nbsp;:</b>&nbsp;<a href="mailto:<?php echo $rs->email;?>"><?php echo $rs->email;?></a></div>
                <div class="subject"><b>Subject&nbsp;:</b>&nbsp;<?php echo $rs->subject;?></div>
                <div class="message"><b>Message&nbsp;:</b>&nbsp;<?php echo $rs->message;?></div>
            </div>
            <hr/>
        <?php } ?>
        </div>
    <?php }
    /**
     * Dashboard pa
     **/
    add_action('wp_dashboard_setup', 'partner_dashboard_widgets');
 
    function partner_dashboard_widgets() {
        wp_add_dashboard_widget('custom_partner', 'Custommer Partner', 'partner_dashboard');
    }

    function partner_dashboard() {
        global $wpdb,$table_prefix;
        $my_query = "SELECT ".$table_prefix."contact.name,".$table_prefix."contact.email,
            ".$table_prefix."contact.subject,".$table_prefix."contact.message,".$table_prefix."contact.time 
            FROM ".$table_prefix."contact  WHERE ".$table_prefix."contact.issue ='partner' 
            ORDER BY ".$table_prefix."contact.time DESC LIMIT 0,10";
        $result = $wpdb->get_results($my_query); ?>
        <div id="published-posts" class="activity-block" style="max-height:340px;overflow:auto;">
        <?php 
        foreach ($result as $rs){ ?>
            <div>
                <div class="name">
                    <span><b>Name&nbsp;:</b>&nbsp;<?php echo $rs->name;?></span>
                    <span>&nbsp;(&nbsp;<?php echo $rs->time;?>&nbsp;)&nbsp;</span>
                </div>
                <div class="emai"><b>Email&nbsp;:</b>&nbsp;<a href="mailto:<?php echo $rs->email;?>"><?php echo $rs->email;?></a></div>
                <div class="subject"><b>Subject&nbsp;:</b>&nbsp;<?php echo $rs->subject;?></div>
                <div class="message"><b>Message&nbsp;:</b>&nbsp;<?php echo $rs->message;?></div>
            </div>
            <hr/>
        <?php } ?>
        </div>
    <?php }
    /**
     * GET USER ROLE NAME
     */
    function cpx_get_user_role_name()
    {
        $user = new WP_User(get_current_user_id());
        return array_shift($user->roles);
    }
    /**
     * Function pagination by jquery
     */
    function pagination_jquery($arr_id , $count_down = 0, $coming = 0, $past = 0, $display){
        $jsons = array();
        foreach ( $arr_id as $id) {
            $link_deal_detail = get_permalink($id);
            $title = get_the_title($id);
            $value_after_saved = round(get_post_meta($id, 'after_discount_metadata', true),2);
            $start_date = get_post_meta($id, 'start_date_metadata', true);
            $end_date = get_post_meta($id, 'end_date_metadata', true);
            $image = get_post_meta($id, 'deal_feature_metadata', true);
            $json['id'] = $id;
            $json['link_deal_detail'] = $link_deal_detail;
            $json['title'] = $title;
            $json['value_after_saved'] = $value_after_saved;
            $json['start_date'] = $start_date;
            $json['end_date'] = $end_date;
            $json['image'] = $image;
            array_push($jsons, $json);
        }
        $response = json_encode($jsons); ?>
                        <script type="text/javascript">
                            function pageselectCallback(page_index, jq){
                                
                                var count_down = <?php echo $count_down?>;
                                var coming = <?php echo $coming?>;
                                var past = <?php echo $past?>;
                                
                                var result = <?php echo $response;?>;
                                var items_per_page = <?php echo $display;?>;
                                var max_elem = Math.min((page_index+1) * items_per_page, result.length);
                                var newcontent = '';
                                for(var i=page_index*items_per_page;i<max_elem;i++)
                                {
                                    newcontent += '<ul class="single-deal"><li>';
                                    newcontent +='<span class="image-wrap">\n\
                                                    <a href="'+result[i]['link_deal_detail']+'" title="'+result[i]['title']+'">\n\
                                                      <img src="'+result[i]['image']+'" title="'+result[i]['title']+'"/>\n\
                                                    </a>\n\
                                                  </span>';
                                    newcontent += '<div class="recent-deal-title">\n\
                                                    <a href="'+result[i]['link_deal_detail']+'" title="'+result[i]['title']+'">'+result[i]['title']+'</a>\n\
                                                  </div>';
                                    newcontent += '<div class="another-timer-block">\n\
                                                     <div id="count_down_'+result[i]['id']+'" class="time-count" data-endtime="'+result[i]['end_date']+'" data-starttime="'+result[i]['start_date']+'">';
                                    newcontent +=    '</div>\n\
                                                   </div>';
                                    newcontent +='</li></ul>';
                                }
                                $('#Searchresult').html(newcontent);
                                if(count_down == 1){
                                    $('div.time-count').each(function(){
                                        var end_date = $(this).data('endtime');
                                            var arr_enddate;
                                            arr_enddate = end_date.split('/');
                                            arr_enddate.join(arr_enddate);
                                            if(arr_enddate.length == 3){
                                                var y = arr_enddate[0];
                                                var m = arr_enddate[1];
                                                var d = arr_enddate[2];
                                                var h = 24;
                                                var end_time = new Date(y, m - 1, d, h);
                                            }
                                        $(this).countdown({
                                            until: end_time
                                        });
                                    });
                                }
                                if(coming == 1){
                                    $('div.time-count').each(function(){
                                        var start_date = $(this).data('starttime');
                                        var html = '<strong>Start&nbsp:&nbsp</strong>' + start_date;
                                        $(this).html(html);
                                    });
                                }
                                return false;
                            }
                            function getOptionsFromForm(){
                                var opt = {callback: pageselectCallback};
                                opt = jQuery.extend({
                                    items_per_page: <?php echo $display; ?>,
                                    num_display_entries:5,
                                    current_page:0,
                                    num_edge_entries:2,
                                    link_to:"#current",
                                    prev_text:"Prev",
                                    next_text:"Next",
                                    ellipse_text:"...",
                                    prev_show_always:true,
                                    next_show_always:true
                            },opt||{});
                                return opt;
                            }
                            jQuery(document).ready(function($) {
                                var result = <?php echo $response;?>;
                                var optInit = getOptionsFromForm();
                                $(".pagination").pagination(result.length,optInit);
                            });
                    </script>
                    <div id="Searchresult">
                        <div class="result-pagination">loading...</div>
                   </div>
                   <div id="Pagination" class="pagination row-fluid"></div>    
    <?php }
    /**
     * RENAME POST >>> DEAL
     */
    function revcon_change_post_label() {
        global $menu;
        global $submenu;
        $menu[5][0] = 'Deals';
        $submenu['edit.php'][5][0] = 'Deals';
        $submenu['edit.php'][10][0] = 'Add Deal';
        $submenu['edit.php'][16][0] = 'Deals Tags';
        echo '';
    }
    function revcon_change_post_object() {
        global $wp_post_types;
        $labels = &$wp_post_types['post']->labels;
        $labels->name = 'Deals';
        $labels->singular_name = 'Deals';
        $labels->add_new = 'Add Deal';
        $labels->add_new_item = 'Add Deal';
        $labels->edit_item = 'Edit Deals';
        $labels->new_item = 'DealS';
        $labels->view_item = 'View Deals';
        $labels->search_items = 'Search Deals';
        $labels->not_found = 'No Deals found';
        $labels->not_found_in_trash = 'No Deals found in Trash';
        $labels->all_items = 'All Deals';
        $labels->menu_name = 'Deals';
        $labels->name_admin_bar = 'Deals';
    }
     
    add_action( 'admin_menu', 'revcon_change_post_label' );
    add_action( 'admin_init', 'revcon_change_post_object' );
    
    //class user
//    {
//        public $name;
//        public function __construct()
//        {
//            echo 'Class '.__CLASS__.' was init <br/>';
//        }
//        public function __toString()
//        {
//            
//        }
//        public function __destruct()
//        {
//            echo 'Class '.__CLASS__.' destroyed <br/>';
//        }
//        public function set($val)
//        {
//            $this->name = $val;
//        }
//        public function get()
//        {
//            return $this->name.'<br/>';
//        }
//    }
//    $u = new user();
//    $u->set('haiht');
//    echo $u->get();
//    exit;